import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

class Message{
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}
@WebServlet("/message")
public class MessageWall extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    private DataSource dataSource = new MysqlDataSource();

    @Override
    public void init() throws ServletException {
        //1. 创建数据源
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/my_message_wall?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //约定 服务器收到客户端请求后，需要返回数据库中的元素
        List<Message> messageList = null;
        try {
            messageList = load();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.setStatus(200);
        resp.setContentType("application/json; charset=utf8");
        //拿到数据库数据后， 通过 Http 协议返回给客户端
        String respJson = objectMapper.writeValueAsString(messageList);
        resp.getWriter().write(respJson);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //约定 通过 json 传输用户信息 - 使用 jackson 解析和打包
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        System.out.println("message=" + message);
        //前端提交信息后，服务器将信息保存到数据库中
        try {
            save(message);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //接收到信息后，服务器给客户端返回一个ok
        resp.setStatus(200);
        resp.getWriter().write("ok");
    }
    private void save(Message message) throws SQLException {
        //1. 建立连接
        Connection connection = dataSource.getConnection();
        //2. 构建 sql 语句
        String sql = "insert into message values(?, ?, ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, message.from);
        preparedStatement.setString(2, message.to);
        preparedStatement.setString(3, message.message);
        //3. 执行 sql 语句
        int n = preparedStatement.executeUpdate();
        System.out.println("n = " + n);
        //4. 释放资源
        preparedStatement.close();
        connection.close();
    }
    private List<Message> load() throws SQLException {
        //元素通过顺序表组织
        List<Message> messageList = new ArrayList<>();
        //1. 建立连接
        Connection connection = dataSource.getConnection();
        //2. 构建 sql 语句
        String sql = "select * from message";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //3. 执行 sql 语句
        ResultSet resultSet = preparedStatement.executeQuery();
        //4. 遍历 sql 语句，组织数据
        while(resultSet.next()){
            Message message = new Message();
            message.from = resultSet.getString("from");
            message.to = resultSet.getString("to");
            message.message = resultSet.getString("message");
            messageList.add(message);
        }
        //5. 关闭资源
        resultSet.close();
        preparedStatement.close();
        connection.close();

        return messageList;
    }
}
